package org.dromara.demo.service;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.demo.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RabbitMQReceiver {
    private final ScheduledExecutorService scheduledExecutorService;
    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void receiveMessage(String message) {
        try {
            //message 转json 对象
            JSONObject jsonObject = JSONObject.parseObject(message);
            //System.out.println("Received message: " + message);
            scheduledExecutorService.schedule(() -> {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage(jsonObject.getString("value"));
                List<Long> userIds = new ArrayList<>();
                userIds.add(jsonObject.getLong("userId"));
                dto.setUserIds(userIds);
                SseMessageUtils.publishMessage(dto);
            }, 1, TimeUnit.NANOSECONDS);
        }catch (Exception e){
            scheduledExecutorService.schedule(() -> {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage(message);
                List<Long> userIds = new ArrayList<>();
                userIds.add(1L);
                dto.setUserIds(userIds);
                SseMessageUtils.publishMessage(dto);
            }, 1, TimeUnit.NANOSECONDS);
            e.printStackTrace();
        }

    }
}
